<?php
    class controller_cart extends __registry_controller
    {
        public $_ = array();
        public $_layout = NULL;
        public $_content_header = 'OPEN';
        public $_content_top = 'OPEN';

        public function __construct()
        {
            parent::add_object(array(
                'handle_string' ,
                'handle_upload' ,
                'handle_paging' ,
                'model_cart' ,
                'handle_validate',
				'handle_permission',
                'model_users' ,
                'model_categories',
                'model_language'
            ));
            $this->_layout = NULL;

        }

        public function index_action()
        {
            $this->per_check_permission();

            $limit = 15;
            $res_html = NULL;
            $seo2 = isset($this->_seokey[2]) ? $this->_seokey[2] : null;
            $enseo = end($this->_seokey);
            if (empty($seo2) || ($seo2 == $enseo && intval($enseo) != 0)) {
                $this->_['url_add'] = URL_BASE . 'admin/' . $this->_seokey[1] . '/' . $this->route->rt_get_seokey_act('add') . '/';
                $this->_['url_edit'] = URL_BASE . 'admin/' . $this->_seokey[1] . '/' . $this->route->rt_get_seokey_act('edit') . '/';
            } else {
                $this->_['url_add'] = URL_BASE . 'admin/' . $this->_seokey[1] . '/' . $this->route->rt_get_seokey_act('add') . '/' . $seo2 . '/';
                $this->_['url_edit'] = URL_BASE . 'admin/' . $this->_seokey[1] . '/' . $this->route->rt_get_seokey_act('edit') . '/' . $seo2 . '/';
            }

            $seo2 = isset($this->_seokey[2]) ? $this->_seokey[2] : null;
            $cid = isset($row['CatID']) ? $row['CatID'] : NULL;
            $this->_['CatName'] = isset($row['CatName']) ? ucwords($row['CatName']) : NULL;
            $html = $this->view->view_display('index');
            $arr_block_html = $this->view->view_get_block_html($html);

            $current = end($this->_seokey) ? intval(end($this->_seokey)) : 1;
            $total = $this->mdc_cart_total_list($cid);

            $url = !empty($cid) ? URL_BASE . $this->_seokey[0] . '/' . $this->_seokey[1] . '/' . $seo2 : URL_BASE . $this->_seokey[0] . '/' . $this->_seokey[1];


            /*xet quyen chuyen tinh trang*/
            $strbtn = "";
            $arrStatus = array(
                "notview" , "process" , "finished" , "checkout" , "cancel" , "delete"
            );
            foreach ($arrStatus as $k => $v) {
                $check = $this->per_check_permission($v , true , null , null);
                if ($check) {
                    $strbtn .= $arr_block_html["btn_" . $v];
                }
            }
            $this->_['btn_tool'] = $strbtn;

            /*end */
            $rows = $this->mdc_cart_list($cid , $current , $limit);

            if (!empty($rows))
                foreach ($rows as $row) {
                    $ID = $row["ID"];
                    $this->_['link_edit_email'.$ID] = "";
                    if ($this->per_check_permission("mail" , true , null , null))
                        $this->_['link_edit_email'.$ID] .= $this->_['url_add'] . $ID . "/" . $row["Status"] . "/" . $row["BuyEmail"];
                    else
                        $this->_['link_edit_email'.$ID] .= "#";

                    $this->_["sent_mail_" . $ID] = $this->_["send_mail"];
                    $this->_["disable" . $ID] = $row["Status"] == "cancel" ? "disabled='disabled'" : "";
                    $row["PostDate"] = date("d/m/Y  h:m:s" , $row["PostDate"]);

                    /*dem so lan gui mail*/

                    $strSentMail = explode(";" , $row["SentMail"]);
                    $j = 0;
                    for ($i = 0 ; $i < count($strSentMail) ; $i++) {
                        if ($strSentMail[$i] == $row["Status"]) {
                            $j = $j + 1;
                        }
                    }


                    if ($j > 0) {
                        $this->_["sent_mail_" . $ID] = $this->_["sent_mail"] . "($j)";
                        $this->_["amount_sent" . $ID] = $j;
                    } else {
                        $this->_["amount_sent" . $ID] = 0;
                    }
                    /*end */

                    /*click vao xem chuyen sang process*/
                    if ($row["Status"] == "notview")
                        $row["Status_v" . $ID] = "process";
                    else
                        $row["Status_v" . $ID] = $row["Status"];
                    /*end*/

                    $res_html .= $this->view->view_assign($arr_block_html['product'] , $row);
                }
            $this->_['paging'] = $this->paging_display($total , $current , $limit , $url , $this->_,"/" , ".html");
            $shtml = $this->view->view_assign_block($html , array('htmlproduct' => $res_html));
            $strOkHtml = $this->view->view_assign($shtml , $this->_);
            return $strOkHtml;
        }

        public
        function index_ajax_action()
        {
           // $this->per_check_permission();

            $this->_layout = 'NO_LAYOUT';
            /*
             * active tinh trang
             * id
             * Email
             * */
            $active = isset($this->_seokey[3]) ? $this->_seokey[3] : null;
            $str_id = isset($this->_seokey[4]) ? $this->_seokey[4] : null;
            $str_path = isset($this->_seokey[5]) ? $this->_seokey[5] : null;
            $ID = isset($this->_seokey[6]) ? $this->_seokey[6] : null;

            /*sent mail*/

            if ($active == 'mail' && !empty($str_id) && !empty($str_path)) {
                $check = $this->per_check_permission("mail" , true , null , null);
                if ($check) {
                    switch ($str_path) {
                        case "notview":
                            $strOkHtml = $this->createHtmlMail($ID , $this->_["mail_content_notview"]);
                            $this->sentMail($str_id , $str_path , $ID , $strOkHtml , $this->_["mail_subject_notview"]);
                            $done = "ok";
                            return $done;
                            break;
                        case "process":
                            $strOkHtml = $this->createHtmlMail($ID , $this->_["mail_content_process"]);
                            $this->sentMail($str_id , $str_path , $ID , $strOkHtml , $this->_["mail_subject_process"]);
                            $done = "ok";
                            return $done;
                            break;
                        case "finished":
                            $strOkHtml = $this->createHtmlMail($ID , $this->_["mail_content_finished"]);
                            $this->sentMail($str_id , $str_path , $ID , $strOkHtml , $this->_["mail_subject_finished"]);
                            $done = "ok";
                            return $done;
                            break;
                        case "checkout":
                            $strOkHtml = $this->createHtmlMail($ID , $this->_["mail_content_checkout"]);
                            $this->sentMail($str_id , $str_path , $ID , $strOkHtml , $this->_["mail_subject_checkout"]);
                            $done = "ok";
                            return $done;
                            break;
                    }
                }
				else
				{
					$done = "NoPermission";
					return $done;
				}
            }

            /*check quyen doi trang thai*/

            $check = $this->per_check_permission($active , true );

            if ($check) {

                if ($active != "delete")
                    $done = $this->mdp_tool_func($this->model , $active , $str_id);
                else

                    $ok = $this->mdp_tool_func($this->model , $active , $str_id);

                if (isset($done) && $done) {
                    $rs = $this->mdc_GetSentMail($str_id);
                    foreach ($rs as $key => $SentMail) {
                        if ($SentMail["SentMail"] != "") {
                            $rsSent = explode(";" , $SentMail["SentMail"]);
                            foreach ($rsSent as $k => $v) {
                                if ($v == "" || $v != $active)
                                    unset($rsSent[$k]);

                            }
                            $arr[$SentMail["ID"]] = count($rsSent);
                        } else {
                            $arr[$SentMail["ID"]] = 0;
                        }
                    }
                    return json_encode($arr);
                } elseif (isset($ok)) {
                    return 'ok';
                }
                else {
                    return 'noOk';
                }
            }
			else 
			{
				return 'NoPermission';
			}

        }


        private function  createHtmlMail($ID , $sms)
        {
            $res_html = "";
            $res_html1 = "";
            $html = $this->view->view_display('MailOrder');
            $arr_block_html = $this->view->view_get_block_html($html);
            $rs = $this->mdc_GetBuyerByID($ID);
            if (!empty($rs)) {
                foreach ($rs as $key => $value) {
                    foreach ($value as $k => $v) {
                        if ($v == NULL) {
                            $value[$k] = "chưa có";
                            $rs[$key] = $value;
                        }
                    }

                }
                foreach ($rs as $row) {
                    $res_html1 .= $this->view->view_assign($arr_block_html['INFO'] , $row);
                }
            }
            $RS = $this->mdc_GetCartDetail($ID);
            $total = 0;
            if (!empty($rs)) {
                $stt = 1;
                foreach ($RS as $row) {
                    $row["stt"] = $stt;
                    $row["Total"] = $row["Price"] * $row["Amount"];
                    $total = $row["Total"] + $total;
                    $row["PostDate"] = date("d/m/Y  h:m:s" , $row["PostDate"]);
                    $res_html .= $this->view->view_assign($arr_block_html['Table'] , $row);
                    $stt = $stt + 1;
                }
            }
            $this->_["Total_a"] = $total;
            $this->_["mail_sent_content"] = $sms;
            $this->_["table"] = $res_html;
            $shtml = $this->view->view_assign_block($html , array('Mail' => $res_html1));
            $strOkHtml = $this->view->view_assign($shtml , $this->_);
            return $strOkHtml;
        }

        private function  sentMail($str_id , $str_path , $ID , $Html , $subject)
        {
            $send_mail = new handle_mail();
            $send_mail->protocol = Emailprotocol;
            $send_mail->parameter = "";
            $send_mail->hostname = Emailhostname;
            $send_mail->username = Emailuser;
            $send_mail->password = Emailpassword;
            $send_mail->port = Emailport;
            $send_mail->mail_set_to(trim($str_id));
            $send_mail->mail_set_from(Emailuser);
            $send_mail->mail_set_sender(Emailuser);
            $send_mail->mail_set_subject(strip_tags(html_entity_decode($subject , ENT_QUOTES , 'UTF-8')));
            $send_mail->setHtml(html_entity_decode($Html , ENT_QUOTES , 'UTF-8'));
            $send_mail->mail_send();
            $rs = $this->mdc_GetSentMail($ID);
            foreach ($rs as $key => $SentMail) {
                $str_path = $SentMail["SentMail"] != "" ? $str_path . ";" . $SentMail["SentMail"] : ";" . $str_path;
            }
            $this->mdc_UpdateSentMail($str_path , $ID);
        }

        public function edit_action()
        {
            $this->per_check_permission();
            $strOkHtml = "";
            $res_html1 = "";
            $res_html2 = "";

            $res_html = NULL;
            $this->_layout = 'iframe';
            $html = $this->view->view_display("editor");
            $arr_block_html = $this->view->view_get_block_html($html);
            $rs = $this->mdc_GetBuyerByID($this->_seokey[3]);
            $arr = array();
            $strOkHtml .= $this->view->view_assign($arr_block_html["cart"] , $arr);
            if (!empty($rs)) {
                foreach ($rs as $key => $value) {
                    foreach ($value as $k => $v) {
                        if ($v == NULL) {
                            $value[$k] = "chưa có";
                            $rs[$key] = $value;
                        }
                    }

                }
                foreach ($rs as $row) {
                    $res_html1 .= $this->view->view_assign($arr_block_html['ShipBuy'] , $row);
                }
            }

            $this->_["DATA_ShipBuy"] = $res_html1;
            $RS = $this->mdc_GetCartDetail($this->_seokey[3]);
            if (!empty($rs)) {
                $stt = 1;
                foreach ($RS as $row) {
                    $row["stt"] = $stt;
                    $row["PostDate"] = date("d/m/Y  h:m:s" , $row["PostDate"]);
                    $res_html2 .= $this->view->view_assign($arr_block_html['table'] , $row);
                    $stt = $stt + 1;
                }
            }
            $this->_["DATA_Table"] = $res_html2;

            $shtml = $this->view->view_assign_block($html , array('htmlCat' => $strOkHtml));
            $strOkHtml = $this->view->view_assign($shtml , $this->_);
            return $strOkHtml;
        }

        public function add_action()
        {
            $this->per_check_permission("mail");
            $this->_["style"] = "display:none";
            $ID = $this->_seokey[3];
            $status = $this->_seokey[4];
            $email = $this->_seokey[5];
            $this->_layout = 'iframe';
            $html = $this->view->view_display("addMail");
            $arr_block_html = $this->view->view_get_block_html($html);
            $shtml = $this->view->view_assign_block($html , array('htmlCat' => $arr_block_html["mail"]));
            if (isset($_POST["mail_subject"]) && isset($_POST["mail_content"])) {

                if ($_POST["mail_subject"] != "" && $_POST["mail_content"] != "") {
                    if (isset($_POST["mail_save"]) && $_POST["mail_save"]) {
                        $content_new = $this->edit_mail($_POST , $status);
                    } else {
                        $content_new = $_POST["mail_content"];
                    }
                    $html = $this->createHtmlMail($ID , $content_new);
                    $this->sentMail($email , $status , $ID , $html , $_POST["mail_subject"]);
                } else {
                    $this->_["style"] = "";
                }
            }

            $this->_["mail_subject_v"] = isset($_POST["mail_subject"]) ? $_POST["mail_subject"] : "";
            $this->_["Status_s"] = $status;
            $this->_["mail_content_v"] = isset($_POST["mail_content"]) ? $_POST["mail_content"] : "";

            $strOkHtml = $this->view->view_assign($shtml , $this->_);
            return $strOkHtml;
        }

        private function  edit_mail($arr , $action)
        {
            $folder = $this->getDirName(LANG);
            $dirlang = PATH_BASE . "app/admin/view/lang/$folder/cart.php";
            include_once($dirlang);
            foreach ($this->_ as $k => $v) {
                if ($k == "mail_content_" . $action) {
                    $this->_ [$k] = $arr["mail_content"];
                }
                if ($k == "mail_subject_" . $action) {
                    $this->_ [$k] = $arr["mail_subject"];
                }
            }

            $new = "<?php\r";
            foreach ($this->_ as $k => $v) {
                $new .= "\$_['$k']='$v';\r";
            }
            $fp = fopen($dirlang , "w")or exit("khong tim thay file can mo");
            fwrite($fp , $new);
            fclose($fp);
            return $this->_["mail_content_" . $action];
        }
    }
